package mail;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.logging.Level;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import models.NewsType;
import models.News;

import com.google.appengine.tools.util.Logging;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.greenlaw110.rythm.Rythm;
import org.apache.commons.codec.binary.Base64;

public class TemplateMail {
    public static void send(String mailTitle, List<String> mailTos, List<News> newses) throws Exception{
        Map<String, Object> context = new HashMap<String, Object>();
        context.put("newses", newses);
        
        // 渲染模版
        String mailBody = Rythm.render("WEB-INF/views/mail.html", context);
        System.out.println(mailBody);

        // 发送邮件
        for (String mailTo : mailTos){
            Properties props = new Properties();
            try{
                Session mailSession = Session.getDefaultInstance(props, null);   
                
                MimeMessage msg = new MimeMessage(mailSession);
                msg.setFrom(new InternetAddress("hahaeason@gmail.com", "Eason Pan"));
                msg.addRecipient(Message.RecipientType.TO,
                                 new InternetAddress(mailTo));
                msg.setSubject(mailTitle, "UTF-8");
                
                Multipart mp = new MimeMultipart();
                MimeBodyPart htmlPart = new MimeBodyPart();
                htmlPart.setContent(mailBody, "text/html");
                mp.addBodyPart(htmlPart);
                msg.setContent(mp);
                
                Transport.send(msg);
            }catch (AddressException e) {
                throw e;
            } catch (MessagingException e) {
                throw e;
            }
        }
    }
    public static void main(String[] args) throws Exception{
        
    }
}
